package com.magiccompass.alipay.barcode.controller;

import java.math.BigDecimal;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.magiccompass.alipay.barcode.entity.UserInfo;
import com.magiccompass.alipay.barcode.security.model.LoginUserModel;
import com.magiccompass.alipay.barcode.service.MerchantBusinessService;
import com.magiccompass.alipay.barcode.signature.MD5Signature;
import com.magiccompass.alipay.barcode.util.UserUtil;

@Controller
@RequestMapping(value="/user")
public class UserController {
	static Logger logger = LogManager.getLogger(UserController.class.getName());
	
	@Resource(name="merchantBusinessService")
	private MerchantBusinessService merchantBusinessService;
	
	@RequestMapping(value="/setting", method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView setting(Model model) {
		 ModelAndView mav = new ModelAndView("user/setting");
	     return mav;
    }
	@RequestMapping(value="/changePwd", method = {RequestMethod.GET,RequestMethod.POST})
    public String changePwd(Model model) {
		LoginUserModel currentUser = UserUtil.getCurrentLoginUser();
		//logger.info(currentUser.getUsername());
		model.addAttribute("userName", currentUser.getDbUserInfo().getUserName());
		model.addAttribute("dbMD5Pwd", currentUser.getDbUserInfo().getPassword());
		return "user/changePwd";
    }
	
	@RequestMapping(value="/changePwdConfirm", method = {RequestMethod.GET,RequestMethod.POST})
    public String changePwdConfirm(Model model,HttpServletRequest request) {
		LoginUserModel currentUser = UserUtil.getCurrentLoginUser();
		String newPwd = request.getParameter("newPwd");
		
		String resultCode = "SUCCESS";
		String resultReason = "Please continue.";

		try {
			UserInfo ui = currentUser.getDbUserInfo();
			ui.setPassword(MD5Signature.getMD5String(newPwd));
			merchantBusinessService.save(ui);
		} catch (Exception e) {
			resultCode = "FAILED";
			resultReason = e.getMessage();
			e.printStackTrace();
		}
		
		String messageType = "alert-danger";
		if("SUCCESS".equals(resultCode)){
			messageType = "alert-success";
		}
		
		String message = "Your operation result is "+resultCode+". "+resultReason;
		
		model.addAttribute("message",message);
		model.addAttribute("messageType",messageType);
        return "common/result";
    }	
}